package com.ywb.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ywb.entity.LoginUser;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
//
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ywb
 * @since 2021/9/21
 */

@RestController
public class LoginController {
    public static final String APP_ID = "wx46f84ffc89bc18a7";
    public static final String APP_SECRET = "bddb0af5d452a9fc23722b98b2f82260";
    @PostMapping("/wxLogin")
    public Map wxLogin(@RequestBody LoginUser loginUser){
        Map<String, Object> result = new HashMap(16);
        String code = loginUser.getCode();

        String openId = getWxOpenId(code, APP_ID, APP_SECRET);

        result.put("code", 200);
        result.put("openId", openId);
        return result;
    }

    private String getWxOpenId(String code, String appId, String appSecret) {
        String url = StrUtil.format("https://api.weixin.qq.com/sns/jscode2session?js_code={}&appid={}&secret={}", code, appId, appSecret);
        JSONObject jsonObject = null;
        try{
            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = client.execute(new HttpGet(url));
            String result = EntityUtils.toString(response.getEntity());
            jsonObject = JSON.parseObject(result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert jsonObject != null : "jsonObject为NULL";
        return jsonObject.getObject("openid", String.class);
    }
}
